package com.rrd.dw.utils;

import java.security.MessageDigest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.hadoop.io.Text;

public class MD5Util {

    private static MessageDigest md5 = null;
    static {
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 用于获取一个String的md5值
     * 
     * @param string
     * @return
     */
    public static String getMd5(String str) {
        byte[] bs = md5.digest(str.getBytes());
        StringBuilder sb = new StringBuilder(40);
        for (byte x : bs) {
            if ((x & 0xff) >> 4 == 0) {
                sb.append("0").append(Integer.toHexString(x & 0xff));
            } else {
                sb.append(Integer.toHexString(x & 0xff));
            }
        }
        return sb.toString();
    }

    public String makeoff(String str, String type) {

        if (str == null || str.length() == 0) {
            return str;
        }
        if (type.equals("pid")) {
            if (str.length() > 14) {
                str = str.substring(0, 10) + "****" + str.substring(14);
            }
        } else if (type.equals("mobile")) {
            if (str.length() > 8) {
                str = str.substring(0, 4) + "****" + str.substring(8);
            }
        } else if (type.equals("telphone")) {
            if (str.length() > 4) {
                str = str.substring(0, 5) + "****";
            }
        } else if (type.equals("telphone")) {
            if (str.length() > 4) {
                str = str.substring(0, 5) + "****";
            }
        } else if (type.equals("email")) {
            if (str.indexOf("@") > 0) {
                str = "****" + str.substring(str.indexOf("@"));
            }
        } else if (type.equals("bank")) {
            if (str.length() > 4) {
                str = "********" + str.substring(str.length() - 4);
            }
        } else if (type.equals("home")) {
            Pattern p = Pattern.compile(".*[0-9]+(楼|号楼|院)(.*)");
            Matcher m = p.matcher(str);
            if (m.find()) {
                System.out.println(m.group(2));
                str = str.replace(m.group(2), "****");
            }
        }

        return str;

    }

    public static void main(String[] args) {
        System.out.println(getMd5("hello word"));
    }

}
